import numpy as np

from shapely.geometry import Polygon, LineString, Point
from shapely.ops import unary_union
from scipy.spatial import Voronoi
from rdp import rdp  # Ramer-Douglas-Peucker 算法
from shapely.geometry.polygon import orient
try:
    from fix_polygon_orientation import fix_shapely_polygon_orientation, is_clockwise, fix_polygon_orientation
except:
    from .fix_polygon_orientation import fix_shapely_polygon_orientation, is_clockwise, fix_polygon_orientation

def spiral_path_generation(boundary_poly, width, min_radius):
    """生成回字型路径 (螺旋向内)"""
    path_lines = []
    #current_poly = local_inner_boundary_poly
    current_poly = boundary_poly.buffer(-width, join_style=2, mitre_limit=5.0)

    #计算最小间隙距离minimum_clearance
    while current_poly.area > 0 and current_poly.minimum_clearance-width > 2*min_radius: #2*min_radius:
        # 生成内缩多边形
        next_poly = current_poly.buffer(-width, join_style=2, mitre_limit=5.0)
        if next_poly.is_empty:
            break

        # 提取边界线
        if current_poly.geom_type == 'Polygon':
            path_lines.append(current_poly.exterior) #exterior外边界
        else:  # MultiPolygon
            for geom in current_poly.geoms:
                path_lines.append(geom.exterior)

        current_poly = next_poly


    for i in range(len(path_lines)):
        polygon = Polygon(path_lines[i])

        oriented_poly = orient(polygon, sign=1 if polygon.area > 0 else -1)

        path_lines[i] = oriented_poly.exterior

        #if polygon.area < 0:#顺时针


    #return unary_union(path_lines)
    return path_lines